
import os,django
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "shareAPI2020TB.settings")# project_name 项目名称
django.setup()
from django.views.generic import  TemplateView
from BaseWeb.models import JDItemId
from BaseWeb.utils.webJWT import JWT_YanZheng_1
from UserAPP.utils import JWTencode
from tbitem.JD_utils.postMain1 import jd_run
from tbitem.JD_utils.wade_Spider_Tool2 import JDSpider
from UserAPP.models import MS_USER
from django.views.decorators.gzip import gzip_page

import os
import random
import re
import time
import requests
from django.shortcuts import reverse, get_object_or_404, get_list_or_404
from django.http import HttpResponse, HttpResponseRedirect
from django.shortcuts import render, redirect

# Create your views here.
from django.utils.safestring import mark_safe
from rest_framework.views import APIView

from tbitem import models as models_tbitem
from shareAPI2020TB.settings import BASE_DIR, log_wade, MESSAGE_global, MEDIA_URL, MEDIA_ROOT
from BaseWeb import models
from tbitem.util import maokoulingClass
from tbitem.util.get_5_postDiscuz import getATitle
from tbitem.util.itemTemplate import ContentFactory_forDjango
from tbitem.views import APIResponse
from tbitem import models as tbitem_models
from django.core.paginator import Paginator, EmptyPage  # 分页

'''流程：
插入：
由某个作者信息（里边有pid）-  tbid 两个共同要素进行配合，生成文本内容
入库
文本内容根据作者信息来进行保存入库

每天定时入库一部分内容

'''
# SEO = {
#     "title":"",
#     "description":"",
#     "keyword":"",
# }

class paging():
    '''
    此为文章分页功能，需要往里传递三个参数，分别如下：
    tablename:表名
    page:页码号，即第几页,这个一般从URL的GET中得到
    pagenum:每页显示多少条记录
    '''
    def __init__(self,tablename,page,pagenum,Categoryid):
        from django.core.paginator import Paginator
        self.tablename = tablename
        self.page = int(page)
        self.pagenum = int(pagenum)
        tn = self.tablename.objects.filter(category__id=Categoryid).all() #查询tablename表中所有记录数，并以降序的方式对id进行排列
        self.p = Paginator(tn,self.pagenum) #对表数据进行分页，每页显示pagenum条
    def pt(self):
        '''共有多少条数据'''
        return self.p.count
    def pn(self):
        '''总页数'''
        return self.p.num_pages
    def pr(self):
        '''获取页码列表'''
        return self.p.page_range
    def pl(self):
        '''第page页的数据列表'''
        return self.p.page(self.page).object_list
    def pp(self):
        '''是否有上一页'''
        return self.p.page(self.page).has_previous()
    def np(self):
        '''是否有下一页'''
        return self.p.page(self.page).has_next()
    def ppn(self):
        '''上一页的页码号'''
        if self.page <= 1: #假如当前页在第一页，那就直接返回1
            return '1'
        else:
            return self.p.page(self.page).previous_page_number()
    def npn(self):
        '''下一页的页码号'''
        if self.p.page(self.page).has_next() == False: #如果当前页不存在下一页，则返回最后一个页码值
            return self.page
        else:
            return self.p.page(self.page).next_page_number()
class FileListpaging():
    '''
    此为文章分页功能，需要往里传递三个参数，分别如下：
    tablename:表名
    page:页码号，即第几页,这个一般从URL的GET中得到
    pagenum:每页显示多少条记录
    '''
    def __init__(self,tablename,page,pagenum,Categoryid):
        from django.core.paginator import Paginator
        self.tablename = tablename
        self.page = int(page)
        self.pagenum = int(pagenum)
        tn = self.tablename.objects.filter(category_type=Categoryid).all() #查询tablename表中所有记录数，并以降序的方式对id进行排列
        print(len(tn))
        self.p = Paginator(tn,self.pagenum) #对表数据进行分页，每页显示pagenum条
    def pt(self):
        '''共有多少条数据'''
        return self.p.count
    def pn(self):
        '''总页数'''
        return self.p.num_pages
    def pr(self):
        '''获取页码列表'''
        return self.p.page_range
    def pl(self):
        '''第page页的数据列表'''
        return self.p.page(self.page).object_list
    def pp(self):
        '''是否有上一页'''
        return self.p.page(self.page).has_previous()
    def np(self):
        '''是否有下一页'''
        return self.p.page(self.page).has_next()
    def ppn(self):
        '''上一页的页码号'''
        if self.page <= 1: #假如当前页在第一页，那就直接返回1
            return '1'
        else:
            return self.p.page(self.page).previous_page_number()
    def npn(self):
        '''下一页的页码号'''
        if self.p.page(self.page).has_next() == False: #如果当前页不存在下一页，则返回最后一个页码值
            return self.page
        else:
            return self.p.page(self.page).next_page_number()


class Detail(APIView):
    authentication_classes = [JWT_YanZheng_1]
    def get(self, request, *args, **kwargs):
        # if request.user ==None:  #这一步验证jwt是否通过，我在webJWT中如果是新用户访问就会设置USER为none，来进行跳转到登陆页面
        #     return render(request, os.path.join(BASE_DIR, 'templates\\login.html'), locals())

        pageId = kwargs.get('page')
        print(pageId)

        querySet = models.DetailPage.objects.filter(pageid=pageId).first()
        if not querySet:
            return render(request, os.path.join(BASE_DIR, 'templates\\error.html'), locals())

        #阅读计数:
        querySet.readNum = querySet.readNum +1
        querySet.save()

        #评论读取：
        CommentQuerySet = models.Comment.objects.filter(comment_detailpage=querySet).all()

        # 获取该页面作者所有的文章列表
        AutherDetailQuerySEt = models.DetailPage.objects.filter(detail_auther=querySet.detail_auther).all()[0:10]

        # # 需要淘宝ID
        #
        # TbIndex_Query = models_tbitem.TbIndex.objects.filter(tbid='576746996711').first()
        # # 生成发帖模板
        # TBimg_Query = models_tbitem.TbIMG.objects.filter(tbimg_Index=TbIndex_Query).all()
        # TBComment_Query = models_tbitem.TbComment.objects.filter(tbComment_Index=TbIndex_Query).all()
        #
        # # def ContentFactory_forDjango(TbIndex_Query, querySet, TBimg_Query, TBComment_Query):
        # htmlContent = ContentFactory_forDjango(TbIndex_Query, querySet, TBimg_Query, TBComment_Query)
        # print(htmlContent)
        # pageHtml = mark_safe('''<a href='/index/' class="list-group-item list-group-item-action">首页</a>''')
        pageHtml = mark_safe(querySet.content)

        #过滤掉html标签,进行选择描述
        pattern = re.compile(r'<[^>]+>', re.S)
        description = pattern.sub('', querySet.content).replace('\n',"").replace("\r", "").replace(" ","").replace("&nbsp","").replace('&gt','')[0:101]

        SEO = {
            "title": "",
            "keywords": "",
            "description": "",
        }
        SEO['title'] = f'狮子庙中学校园网'
        SEO['keywords'] = f'狮子庙中学校园网'
        SEO['description'] = f'狮子庙中学校园网'




        # querySet.tbid
        # querySet.title
        # querySet.content
        # querySet.tags
        # querySet.date
        return render(request, os.path.join(BASE_DIR, 'templates\\detail.html'), locals())


class Vip(APIView):
    authentication_classes = [JWT_YanZheng_1]
    def get(self, request, *args, **kwargs):
        if request.user ==None:  #这一步验证jwt是否通过，我在webJWT中如果是新用户访问就会设置USER为none，来进行跳转到登陆页面
            return render(request, os.path.join(BASE_DIR, 'templates\\login.html'), locals())
        return render(request, os.path.join(BASE_DIR, 'templates\\vip.html'), locals())


class editor(APIView):  #文章发布页
    authentication_classes = [JWT_YanZheng_1]
    def get(self, request, *args, **kwargs):
        if request.user ==None:  #这一步验证jwt是否通过，我在webJWT中如果是新用户访问就会设置USER为none，来进行跳转到登陆页面
            return render(request, os.path.join(BASE_DIR, 'templates\\login.html'), locals())

        #渲染二级分类
        category_typeQuerySet = models.Category.objects.filter(category_type=1).all()
        print(category_typeQuerySet)
        return render(request, os.path.join(BASE_DIR, 'templates\\page\\editor.html'), locals())


class EditorPost(APIView):
    authentication_classes = [JWT_YanZheng_1]
    '''发文模块'''
    def get(self, request, *args, **kwargs):
        WarningWord = "请用post方法提交"

        return render(request, os.path.join(BASE_DIR, 'templates\\page\\editor.html'), locals())

    def post(self, request, *args, **kwargs):
        WarningWord = "文章发布页面"
        if request.user ==None:  #这一步验证jwt是否通过，我在webJWT中如果是新用户访问就会设置USER为none，来进行跳转到登陆页面
            return render(request, os.path.join(BASE_DIR, 'templates\\login.html'), locals())
        print(request.user['username'])
        title = request.data.get('title')   #form表单
        body = request.data.get('body')     #form表单
        postTime = request.data.get('datetimepicker')    #form表单
        readNum = int(request.data.get('readNum'))    #form表单
        category_id = int(request.data.get('category'))    #form表单
        if postTime =="":
            WarningWord = "未填写时间"
            return render(request, os.path.join(BASE_DIR, 'templates\\page\\editor.html'), locals())

        # print(title, body,postTime)

        # 随机获得作者，数据表有绑定获得由pid和喵口令id，用来发帖
        querySetAuthorList = models.MS_USER.objects.all()
        if not querySetAuthorList:
            models.MS_USER.objects.get_or_create(id=0)
            querySetAuthorList = models.MS_USER.objects.all()
        querySetAuthor = random.choice(querySetAuthorList)
        print(querySetAuthor.nickName)


        DetailPageQuerySet = models.DetailPage.objects.create(
            tbid=123,
            detail_auther=querySetAuthor,
            title=title,
            content=body,
            tags='',
            date = postTime,
            readNum =readNum,
            category_id=category_id,
        )
        DetailPageQuerySet.save()

        response = HttpResponseRedirect(reverse("index"))
        return response

class ExitUser(APIView):
    #清除cookie的token，然后重定向到登陆页面
    authentication_classes = [JWT_YanZheng_1]
    def get(self, request, *args, **kwargs):
        response = HttpResponseRedirect(reverse("Login"))
        response.delete_cookie('token')
        return response

class JDComment(APIView):  #最火的评论
    authentication_classes = [JWT_YanZheng_1]
    def get(self, request, *args, **kwargs):
        if request.user ==None:  #这一步验证jwt是否通过，我在webJWT中如果是新用户访问就会设置USER为none，来进行跳转到登陆页面
            return render(request, os.path.join(BASE_DIR, 'templates\\login.html'), locals())
        # tbid = 564040402399
        pages = 3  # 到淘宝爬取评论
        STATE = '数据库id状态'
        jdid = request.query_params.get('id')
        if not jdid:
            jdid = 100002608347
            STATE = '样板'
        print(jdid)
        STATE = '已经用过的id'
        #查询数据
        queryJDid = JDItemId.objects.filter(jDid=jdid).first()
        if not queryJDid:
            #数据库没有数据的话，入库
            STATE = '新id'
            JDItemId.objects.create(jDid=jdid).save()
            queryJDid = JDItemId.objects.filter(jDid=jdid).first()
        elif queryJDid.jDid == str(100002608347):
            pass


        print(queryJDid)
        print('123123')
        # else:
        #     return HttpResponse(STATE)


        # 爬虫类初始化，获取图片和评论列表
        commentList,imgList,comments_p,imglists_p = [],[],[],[]
        for i in range(0,5):  #爬0到5页
            comments_p, imglists_p, results = JDSpider().spider_comment(queryJDid.jDid, i)
            if comments_p ==[]:
                continue
            commentList.extend(comments_p)
            imgList.extend(imglists_p)
            WarningWord = results
        del comments_p,imglists_p

        # 爬虫类初始化，获取图片和评论列表-END

        commentZip = zip(commentList,imgList)


        #爬取 商品详细参数
        itemDataList = JDSpider().spider_itemData(queryJDid.jDid)
        itemList = []
        goodName = ''
        for items in itemDataList:
            itemName = items[1]
            itemContent = items[2]
            if "href" in itemContent:
                continue
            if "商品名称" in itemName:
                goodName = items[2]
            itemList.append({"itemName":itemName,"itemContent":itemContent})
        print(itemList)
        print(goodName)
        #爬取 商品详细参数---End

        # 爬取问答：Begin  askList结构看函数里边有
        askList = JDSpider().spider_itemQueston(queryJDid.jDid)
        # 爬取问答：End


        return render(request, os.path.join(BASE_DIR, 'templates\\page\\JDComment.html'), locals())



#最新的评论
class JDComment_NewComment(APIView):
    authentication_classes = [JWT_YanZheng_1]
    def get(self, request, *args, **kwargs):
        if request.user ==None:  #这一步验证jwt是否通过，我在webJWT中如果是新用户访问就会设置USER为none，来进行跳转到登陆页面
            return render(request, os.path.join(BASE_DIR, 'templates\\login.html'), locals())
        account = MS_USER.objects.filter(USERNAME=request.user['username']).first()

        # tbid = 564040402399
        pages = 50  # 到淘宝爬取评论
        STATE = '数据库id状态样本100002608347'
        jdid = request.query_params.get('id')
        category_id = request.query_params.get('category')

        #渲染二级分类
        category_typeQuerySet = models.Category.objects.filter(category_type=1).all()


        if not jdid:

            # jdid = 100002608347
            # STATE = '样板'
            return render(request, os.path.join(BASE_DIR, 'templates\\page\\JDComment.html'), locals())

        STATE = '已经用过的id'
        #查询数据
        queryJDid = JDItemId.objects.filter(jDid=jdid).first()
        if not queryJDid:
            #数据库没有数据的话，入库
            STATE = '新id'
            JDItemId.objects.create(jDid=jdid).save()
            queryJDid = JDItemId.objects.filter(jDid=jdid).first()
        elif queryJDid.jDid == str(100002608347):
            pass


        # print(queryJDid)
        # print('123123')
        # else:
        #     return HttpResponse(STATE)


        # 爬虫类初始化，获取图片和评论列表
        commentList,imgList,comments_p,imglists_p = [],[],[],[]
        for i in range(0,pages):  #爬0到PAGE要求页
            comments_p, imglists_p, results = JDSpider().spider_Newcomment(queryJDid.jDid, i)
            if comments_p ==[]:
                continue
            commentList.extend(comments_p)
            imgList.extend(imglists_p)
            if len(commentList) >= 20 and len(imgList) >=20:
                break
            WarningWord = results
        del comments_p,imglists_p

        

        
        # 爬虫类初始化，获取图片和评论列表-END

        commentZip = zip(commentList,imgList)


        #爬取 商品详细参数
        itemDataList = JDSpider().spider_itemData(queryJDid.jDid)
        itemList = []
        goodName = ''
        for items in itemDataList:
            itemName = items[1]
            itemContent = items[2]
            if "href" in itemContent:
                continue
            if "商品名称" in itemName:
                goodName = items[2]
            itemList.append({"itemName":itemName,"itemContent":itemContent})
        # print(itemList)
        # print(goodName)
        #爬取 商品详细参数---End

        # 爬取问答：Begin  askList结构看函数里边有
        askList = JDSpider().spider_itemQueston(queryJDid.jDid)
        # 爬取问答：End


        """本站发帖"""
        def webTask():
            # 文章在本网站也发一次贴,不能影响主要任务进程

            try:

                userObj = MS_USER.objects.filter(USERNAME=request.user['username']).first()  #获取用户对象，用户对象关联着喵口令

                jd = jd_run(userOBJ=userObj)
                jd.imgList = imgList
                jd.title = goodName + "好不好怎么样？"
                jd.category_id = category_id
                jd.commentList = commentList
                jd.initBySkuID(queryJDid)
                jd.web()

            except Exception as e:
                print(e)
                log_wade.error(e)
                pass

        import threading
        # 创建新线程
        if jdid != 100002608347:
            thread1 = threading.Thread(target=webTask, args=())
            # 启动线程
            thread1.start()
        """本站发贴---End"""


        return render(request, os.path.join(BASE_DIR, 'templates\\page\\JDComment.html'), locals())





#从excel读取数据，输出文本格式的内容

# class ShopDetail(APIView):
#     authentication_classes = [JWT_YanZheng_1]
#     def get(self, request, *args, **kwargs):
#         if request.user ==None:  #这一步验证jwt是否通过，我在webJWT中如果是新用户访问就会设置USER为none，来进行跳转到登陆页面
#             return render(request, os.path.join(BASE_DIR, 'templates\\login.html'), locals())
#
#         document = Document()
#         df = pd.read_excel(os.path.join(BASE_DIR,'media','产品参数.xls'),
#             keep_default_na=False,
#             # converters={"身份证号":str,"卡号":str},
#
#             sheet_name=0
#
#         )  # 这个会直接默认读取到这个Excel的第一个表单
#
#         def getDictFrom(df):
#             df_dict = []
#             for i in df.index.values:
#                 df_dict.append(df.loc[i].to_dict())  # 将title和每行数据以字典的形式组装
#             return df_dict
#
#         data = getDictFrom(df.T)
#         print(df)
#         return render(request, os.path.join(BASE_DIR, 'templates\\page\\ShopDetail.html'), locals())


class WebIndex(APIView):
    authentication_classes = [JWT_YanZheng_1]
    # authentication_classes = []
    def get(self, request, *args, **kwargs):
        log_wade.error(f"你进入了主页")
        # if request.user ==None:  #这一步验证jwt是否通过，我在webJWT中如果是新用户访问就会设置USER为none，来进行跳转到登陆页面
        #     return render(request, os.path.join(BASE_DIR, 'templates\\login.html'), locals())

        # fenleiList = get_list_or_404(models.Category, category_type=0)  # 获取一级类目列表
        def getList(code):
            CategoryQuery = models.Category.objects.filter(category_type=1, code=code).first()
            if not CategoryQuery:
                models.Category.objects.create(category_type=1, code=code)
                CategoryQuery = models.Category.objects.filter(category_type=1, code=code).first()
            boardTitleList = models.DetailPage.objects.filter(category__code=CategoryQuery.code).all()[0:10]  # 获得某一个栏目下的所有文章
            return boardTitleList,CategoryQuery

        # board1
        # boardList1,CategoryQuery1 = getList(1)
        # boardList2,CategoryQuery2 = getList(2)
        # boardList3,CategoryQuery3 = getList(3)
        # boardList4,CategoryQuery4 = getList(4)
        # boardList5,CategoryQuery5 = getList(5)
        # boardList6,CategoryQuery6 = getList(6)




        categoryList =[]
        categoryList_lv1_Query = models.Category.objects.filter(category_type=0).all()
        # for item in categoryList_lv1_Query:
        #     print(item.get_sub_categorys())
        fileListQuery = models.UpLoadFile.objects.filter(category_type=0).all()
        if request.user:
            account = MS_USER.objects.filter(USERNAME = request.user['username']).first()
        return render(request, os.path.join(BASE_DIR, 'templates\\web\\webIndex.html'), locals())


class webUpload(APIView):  #上传文件页面
    authentication_classes = [JWT_YanZheng_1]
    # authentication_classes = []
    def get(self, request, *args, **kwargs):
        return render(request, os.path.join(BASE_DIR, 'templates\\web\\webUpload.html'), locals())
class SaveUpload(APIView):  #存储上传内容
    authentication_classes = [JWT_YanZheng_1]
    # authentication_classes = []
    def post(self, request, *args, **kwargs):
        log_wade.error(f"你进入了主页")
        if request.method == 'POST':
            imgFile = request.FILES['good']

            Categoryid = kwargs.get('Categoryid')  # 获取首页的跳转链接分类
            if not Categoryid:
                Categoryid = 1
            print(Categoryid)
            # 判断提交的id，通过category_type，分发文件夹  0通用 1安全 3、活动

            UpLoadFileQuerySet = models.UpLoadFile.objects.create(
                fileName =imgFile.name,
                file =imgFile,
                category_type =0,
                category =models.Category.objects.filter(id = Categoryid).first(),
            )
            UpLoadFileQuerySet.save()
            fileQuery = models.UpLoadFile.objects.all().first()
            print(fileQuery.id)
            print(fileQuery.file)
            return APIResponse({'id':fileQuery.id,'file':str(fileQuery.file),'fileName':fileQuery.fileName,'category_type':fileQuery.category_type,'date':fileQuery.date},msg=f'保存成功')




class WebList(APIView):
    '''路径： 访问index ——jwt验证是否有token或者是否正确-不正确->user赋值NONE--->跳转到login登陆'''
    authentication_classes = [JWT_YanZheng_1]
    # authentication_classes = []
    def get(self, request, *args, **kwargs):


        if request.user:  #这一步验证jwt是否通过，我在webJWT中如果是新用户访问就会设置USER为none，来进行跳转到登陆页面
            account = MS_USER.objects.filter(USERNAME=request.user['username']).first()


        Categoryid = kwargs.get('Categoryid')  #获取首页的跳转链接分类
        pagenum = kwargs.get('page')  #获取首页的跳转链接页码

        # 分页程序
        if not pagenum:  #如果没有页码值，默认是第一页
            pagenum = 1
        if not Categoryid:
            Categoryid = 1
        p = paging(models.UpLoadFile, pagenum, 19,Categoryid)  # 创建分页的实例，并传递相关的参数进去，Task是任务表名，Pa是当前页数，19表示每页显示19条数据
        pn = p.pn()  # 总页数
        pt = p.pt()  # 共有多少条数据
        pl = p.pl()  # 第x页的数据列表
        pp = p.pp()  # 是否有前一页
        np = p.np()  # 是否有后一页
        ppn = p.ppn()  # 前一页页码
        npn = p.npn()  # 后一页页码

        cp = int(pagenum)  # 获取当前页，并转为型形，方便下面进行计算和比较，并且模板文件中也要用到比较
        if cp < 5:  # 这里进行判断，假如当前页小于5的时候，
            pr = p.pr()[0:9]  # pr为获取页码列表，即当前页小于5的时候，模板中将显示第1页至第9页，如 1 2 3 4 5 6 7 8 9
        elif int(pn) - cp < 5:  # 假如最后页减当前页小于5时
            pr = p.pr()[int(pn) - 7:int(pn)]  # 页码列表显示最后9页，如共有30页的话，那显示：22 23 24 25 26 27 28 29 30
        else:  # 其它情况
            pr = p.pr()[cp - 4:cp + 4]  # 其它情况显示当前页的前4条至后4条，如当前在第10页的话，那显示：6 7 8 9 10 11 12 13 14


        querySet = p.pl()  #分页后的列表单元组

        #SEO优化
        SEO = {"title": "","keywords": "","description": "",}
        SEO['title'] = f'狮子庙中学校园网'
        SEO['keywords'] = f'狮子庙中学校园网'
        SEO['description'] = f'狮子庙中学校园网'

        print(SEO)

        CategoryItemQuery = models.Category.objects.filter(id=Categoryid).first()
        Category_name = CategoryItemQuery.name
        parent_Category_name = CategoryItemQuery.parent_category.name
        return render(request, os.path.join(BASE_DIR, 'templates\\web\\webList.html'), locals())


    # 需要 pid tbid,这个目的是为了发到本地贴内，返回符合的内容和评论合集，可以实现
class FileList(APIView):
    '''路径： 访问index ——jwt验证是否有token或者是否正确-不正确->user赋值NONE--->跳转到login登陆'''
    authentication_classes = [JWT_YanZheng_1]
    # authentication_classes = []
    def get(self, request, *args, **kwargs):
        log_wade.error(f"你进入了主页")
        # if request.user ==None:  #这一步验证jwt是否通过，我在webJWT中如果是新用户访问就会设置USER为none，来进行跳转到登陆页面
        #     return render(request, os.path.join(BASE_DIR, 'templates\\login.html'), locals())

        Categoryid = kwargs.get('Categoryid')  #获取首页的跳转链接分类
        pagenum = kwargs.get('page')  #获取首页的跳转链接页码
        print(Categoryid)
        print(pagenum)
        # 分页程序
        if not pagenum:  #如果没有页码值，默认是第一页
            pagenum = 1
        if not Categoryid:
            Categoryid = 0
        p = FileListpaging(models.UpLoadFile, pagenum, 19,Categoryid)  # 创建分页的实例，并传递相关的参数进去，Task是任务表名，Pa是当前页数，19表示每页显示19条数据
        pn = p.pn()  # 总页数
        pt = p.pt()  # 共有多少条数据
        pl = p.pl()  # 第x页的数据列表
        pp = p.pp()  # 是否有前一页
        np = p.np()  # 是否有后一页
        ppn = p.ppn()  # 前一页页码
        npn = p.npn()  # 后一页页码

        cp = int(pagenum)  # 获取当前页，并转为型形，方便下面进行计算和比较，并且模板文件中也要用到比较
        if cp < 5:  # 这里进行判断，假如当前页小于5的时候，
            pr = p.pr()[0:9]  # pr为获取页码列表，即当前页小于5的时候，模板中将显示第1页至第9页，如 1 2 3 4 5 6 7 8 9
        elif int(pn) - cp < 5:  # 假如最后页减当前页小于5时
            pr = p.pr()[int(pn) - 7:int(pn)]  # 页码列表显示最后9页，如共有30页的话，那显示：22 23 24 25 26 27 28 29 30
        else:  # 其它情况
            pr = p.pr()[cp - 4:cp + 4]  # 其它情况显示当前页的前4条至后4条，如当前在第10页的话，那显示：6 7 8 9 10 11 12 13 14


        querySet = p.pl()  #分页后的列表单元组

        #SEO优化
        SEO = {"title": "","keywords": "","description": "",}
        SEO['title'] = f'狮子庙中学校园网'
        SEO['keywords'] = f'狮子庙中学校园网'
        SEO['description'] = f'狮子庙中学校园网'

        print(SEO)



        return render(request, os.path.join(BASE_DIR, 'templates\\web\\webList.html'), locals())


    # 需要 pid tbid,这个目的是为了发到本地贴内，返回符合的内容和评论合集，可以实现
class delsaveUploadList(APIView):
    '''路径： 访问index ——jwt验证是否有token或者是否正确-不正确->user赋值NONE--->跳转到login登陆'''
    authentication_classes = [JWT_YanZheng_1]
    # authentication_classes = []
    def post(self, request, *args, **kwargs):
        # log_wade.error(request.user)
        # print(request.user)
        if request.user ==None:  #这一步验证jwt是否通过，我在webJWT中如果是新用户访问就会设置USER为none，来进行跳转到登陆页面

            return render(request, os.path.join(BASE_DIR, 'templates\\login.html'), locals())
        account = MS_USER.objects.filter(USERNAME=request.user['username']).first()
        id = kwargs.get('id')  #获取首页的跳转链接分类
        pagenum = kwargs.get('page')  #获取首页的跳转链接页码
        print(id)
        print(pagenum)
        # 分页程序
        if not pagenum:  #如果没有页码值，默认是第一页
            pagenum = 1
        if not id:
            id = 0
        query_id = models.UpLoadFile.objects.filter(id=id).first()


        models.UpLoadFile.objects.filter(id=id).delete()  #删除语句

        if os.path.exists(query_id.file.path):
            os.remove(query_id.file.path)
        log_wade.error(f"{request.user['username']} 删除了 {query_id.fileName}")  #记录谁删了内容
        # return render(request, os.path.join(BASE_DIR, 'templates\\web\\webIndex.html'), locals())
        return APIResponse(0,msg=1)


    # 需要 pid tbid,这个目的是为了发到本地贴内，返回符合的内容和评论合集，可以实现


class Login(APIView):
    authentication_classes = []
    '''登陆模块，输入账户密码获得内容'''
    def get(self, request, *args, **kwargs):
        SEO = {
            "title": "",
            "keywords": "",
            "description": "",
        }
        SEO['title'] = f'狮子庙中学校园网'
        SEO['keywords'] = f'狮子庙中学校园网'
        SEO['description'] = f'狮子庙中学校园网'

        return render(request, os.path.join(BASE_DIR, 'templates\\login.html'), locals())
    def post(self, request, *args, **kwargs):
        username = request.data.get('username')
        password = request.data.get('password')
        print(username, password)
        userObj = MS_USER.objects.filter(USERNAME=username, PASSWORD=password).first()
        if not userObj:
            mymsg = "没有该用户，小屁屁是不是改挨打了？？"
            return render(request, os.path.join(BASE_DIR, 'templates\\login.html'), locals())
        token = JWTencode.createToken({'user_id': userObj.ID, 'username': username}, 100000)
        print(token)
        response = HttpResponseRedirect(reverse("index"))
        response.set_cookie('token', token)
        return response



class Search(APIView):
    '''路径： 访问index ——jwt验证是否有token或者是否正确-不正确->user赋值NONE--->跳转到login登陆'''
    authentication_classes = [JWT_YanZheng_1]
    # authentication_classes = []
    def get(self, request, *args, **kwargs):
        log_wade.error(f"你进入了主页")
        # if request.user ==None:  #这一步验证jwt是否通过，我在webJWT中如果是新用户访问就会设置USER为none，来进行跳转到登陆页面
        #     return render(request, os.path.join(BASE_DIR, 'templates\\login.html'), locals())

        pagenum = kwargs.get('page')
        if not pagenum:  #如果没有页码值，默认是第一页
            pagenum = 1
        p = paging(models.DetailPage, pagenum, 19)  # 创建分页的实例，并传递相关的参数进去，Task是任务表名，Pa是当前页数，19表示每页显示19条数据
        pn = p.pn()  # 总页数
        pt = p.pt()  # 共有多少条数据
        pl = p.pl()  # 第x页的数据列表
        pp = p.pp()  # 是否有前一页
        np = p.np()  # 是否有后一页
        ppn = p.ppn()  # 前一页页码
        npn = p.npn()  # 后一页页码
        cp = int(pagenum)  # 获取当前页，并转为型形，方便下面进行计算和比较，并且模板文件中也要用到比较
        if cp < 5:  # 这里进行判断，假如当前页小于5的时候，
            pr = p.pr()[0:9]  # pr为获取页码列表，即当前页小于5的时候，模板中将显示第1页至第9页，如 1 2 3 4 5 6 7 8 9
        elif int(pn) - cp < 5:  # 假如最后页减当前页小于5时
            pr = p.pr()[int(pn) - 7:int(pn)]  # 页码列表显示最后9页，如共有30页的话，那显示：22 23 24 25 26 27 28 29 30
        else:  # 其它情况
            pr = p.pr()[cp - 4:cp + 4]  # 其它情况显示当前页的前4条至后4条，如当前在第10页的话，那显示：6 7 8 9 10 11 12 13 14
        DetailPage_querySet = models.DetailPage.objects.all()
        # print(querySet.pageid)
        # pageid = querySet.pageid
        paginator = Paginator(DetailPage_querySet, 5)
        print(paginator.num_pages)

        """
        """
        querySet = p.pl()

        #SEO优化
        SEO = {
            "title": "",
            "keywords": "",
            "description": "",
        }
        SEO['title'] = f'狮子庙中学校园网'
        SEO['keywords'] = f'狮子庙中学校园网'
        SEO['description'] = f'狮子庙中学校园网'

        print(SEO)
        return render(request, os.path.join(BASE_DIR, 'templates\\search.html'), locals())


    # 需要 pid tbid,这个目的是为了发到本地贴内，返回符合的内容和评论合集，可以实现
def addWEbContent():
    userObj = MS_USER.objects.all().first()  # 获取用户对象，用户对象关联着喵口令
    jd = jd_run(userOBJ=userObj)
    jd.imgList = ['']
    jd.commentList = ['']
    jd.initBySkuID(100005404692)
    jd.web()




class Redirect(APIView):
    # 请求范例
    'http://127.0.0.1:8000/content/type(1是商品，2是店铺)/淘宝id/时间戳'

    def get(self, request, *args, **kwargs):
        type = kwargs.get('type')  #获取链接类型，1是tb商品链接，2是淘宝店铺链接
        tbid  = kwargs.get('id')
        record_time = kwargs.get('time')  #获取生成链接当时的时间戳
        if len(str(record_time)) != 10:
            record_time = int(time.time())  #如果给的是错误的时间戳，那么认为是现在刚发的，给一个7天以内

        if len(str(tbid)) != 10:
            return render(request, os.path.join(BASE_DIR, 'templates\\index.html'), locals())

        timeNow = int(time.time())
        passTime = timeNow-record_time

        if passTime <86400 and passTime>=0:

            #根据tbid搜索帖子，如果有帖子，就反馈给前台，如果没有，就返回主页
            DetailPage_Queryset = models.DetailPage.objects.filter(tbid=tbid).first()
            if not DetailPage_Queryset:
                print('数据库中没有对应的tbid')
                return render(request, os.path.join(BASE_DIR, 'templates\\index.html'), locals())
            else:
                print('返回对应的内容页')
                print(str(DetailPage_Queryset.pageid))
                # return HttpResponseRedirect(reverse("detail",kwargs={"page":6}))
                return redirect(reverse("detail",kwargs={"page":6}))
                # return redirect(os.path.join(BASE_DIR,'detail\\6\\'))
            # return HttpResponse(f'{passTime}7天以内展示站内落地页')
        else:
            # 根据拿到的tbid进行url转换，转成淘宝链接进行扩展
            return redirect('https://www.baidu.com/')
        # print("当前时间： ", time.strftime('%Y.%m.%d %H:%M:%S ', time.localtime(time.time())))

        # return HttpResponse(passTime)

def getpan():
    payload = {
        'surl': '1ygvXDWluSAyA8gPy4jaYJA',
        'pwd': 'ko9g',
        'Password': 'laochuan',
    }
    mysession = requests.session()
    html = mysession.post('http://laochuan520.cn/pan/',data=payload)
    print(html.text)

    if '重要提示","请勿将密码告诉他人！此项目仅供测试使用' in html.text:
        print("获取到接口网页")
        if re.findall("(\d+)',(\d+),'(.*?)','(.*?)','(\d+)','(\d+)", html.text) != []:  # 如果不为空就是找到了
            re_result = re.findall("(\d+)',(\d+),'(.*?)','(.*?)','(\d+)','(\d+)", html.text)
            print(re_result)
            fs_id = re_result[0][0]
            gettime = re_result[0][1]
            sign = re_result[0][2]
            randsk = re_result[0][3]
            share_id = re_result[0][4]
            uk = re_result[0][5]
            headers = {
                'Content-Type': 'application/x-www-form-urlencoded',
            }

            data = {
                'fs_id':fs_id,
                'time':gettime,
                'sign':sign,
                'randsk':randsk,
                'share_id':share_id,
                'uk':uk
            }
            print(f'fs_id={fs_id}&time={gettime}&sing={sign}&randsk={randsk}&shar_id={share_id}&uk={uk}')
            # print(params)
            result_html = mysession.post('http://laochuan520.cn/pan/?download',params=data)
            print(result_html.text)

class Pan(APIView):
    def get(self, request, *args, **kwargs):
        return render(request, os.path.join(BASE_DIR, 'templates\\onePage\\1.html'), locals())

if __name__ == '__main__':
    # getpan()

    print(int(time.time()))